package com.uwantsoft.interfaces.web.controller.web;

import com.uwantsoft.business.facade.CityFacadeImpl;
import com.uwantsoft.business.facade.ParkingFacadeImpl;
import com.uwantsoft.business.facade.dto.parking.ParkDetailDto;
import com.uwantsoft.business.facade.dto.parking.ParkFormDto;
import com.uwantsoft.business.facade.dto.parking.ParkOverviewQueryCondition;
import com.uwantsoft.util.paging.DefaultPaginatedList;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @author LeiPeichen.
 */
@Controller(value = "parkController")
@RequestMapping(value = "/backend")
public class ParkController {
    @Resource(name = "parkingFacade")
    private ParkingFacadeImpl parkingFacade;

    @Resource(name="cityFacade")
    private CityFacadeImpl cityFacade;

    @RequestMapping(value = "parkoverview")
    public String obtainParks(ParkOverviewQueryCondition parkOverviewQueryCondition,Model model){
        DefaultPaginatedList defaultPaginatedList = parkingFacade.obtainParkByPage(parkOverviewQueryCondition);
        model.addAttribute("defaultPaginatedList",defaultPaginatedList);
        return "backend/parkoverview";
    }
    @RequestMapping(value = "park",method = RequestMethod.POST)
    public String addOrUpdate(@Valid ParkFormDto parkFormDto,BindingResult bindingResult,Model model){
        if(bindingResult.hasErrors()){
            model.addAttribute("cities", cityFacade.obtainCities());
            return "backend/parkform";
        }
        parkingFacade.addOrUpdate(parkFormDto);
        return "redirect:parkoverview";
    }
    @RequestMapping(value = "parkform")
    public String obtainParkForm(String guid,Model model){
        ParkFormDto parkFormDto =  parkingFacade.obtainPark(guid);
        model.addAttribute("parkFormDto", parkFormDto);
        model.addAttribute("cities", cityFacade.obtainCities());
        return "backend/parkform";
    }

    @RequestMapping(value = "parkdetail")
    public String obtainParkDetail(String guid,Model model){
        ParkDetailDto parkDetailDto = parkingFacade.obtainParkDetail(guid);
        model.addAttribute("parkDetailDto",parkDetailDto);
        return "backend/parkdetail";
    }
    @RequestMapping(value = "lockpark")
    public String lockPark(String guid, boolean lock,ParkOverviewQueryCondition parkOverviewQueryCondition,Model model){
        parkingFacade.lockPark(guid, lock);
        model.addAttribute("name",parkOverviewQueryCondition.getName());
        model.addAttribute("page", parkOverviewQueryCondition.getPage());
        return "redirect:parkoverview";
    }
}
